'use strict';

var model = require('../../model/vendor.js');
var debug = require('debug')('dao_vendor_impl');
var appUtils = require('../../common/app_utils.js');
var errInfo = require('../../common/err_info.js');
var md5 = appUtils.md5;
var fout = appUtils.formatOutput;
var ferror = appUtils.formatError;


function DaoImpl() {
	var self = this instanceof DaoImpl ? this : new DaoImpl();
	return self;
}

module.exports = new DaoImpl();
var theProto = DaoImpl.prototype;

theProto.create = function(json) {
	debug('create ', json);
	// TODO check
	var item = new model({
		name: json.name
	});

	return item.save()
		.then(function(result) {
			return fout(result);
		}, function(err) {
			if (err.code === 11000) {
				return ferror(__errDuplicate(err.errmsg));
			}
			return ferror(err.code, 'mongodb error: ' + err.errmsg);
		});
};

// handle error info
function __errDuplicate(errmsg) {
	var ptnName = /name/g;
	if (ptnName.exec(errmsg)) {
		return errInfo.E2300;
	}
}

var __defaultProject = {
	__v: 0
};